package com.sfang.common.extension;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.sfang.common.util.dingTalk.DingTalkUtil;
import com.sfang.common.util.log.LogUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.Arrays;

@Component
public class CustomLogbackFilter extends Filter<ILoggingEvent> {
    @Autowired
    Environment env;

    @Value("${spring.application.name:}")
    private String applicationName;

    private static String appKey;
    private static Environment environment;

    @Value("${jt.current.profile:}")
    private String profile;

    private static String enviromentType;

    @PostConstruct
    public void init() {
        this.environment= env;
        this.appKey = applicationName;

        if (environment != null && environment.getProperty("env") != null)
            this.enviromentType = environment.getProperty("env");
        else if (environment != null && environment.getProperty("spring.cloud.config.profile") != null)
            this.enviromentType = environment.getProperty("spring.cloud.config.profile");
        else if (profile != null && profile.length() > 0)
            this.enviromentType = profile;

    }

    @Override
    public FilterReply decide(ILoggingEvent event) {

        String[] excluded = environment != null && environment.getProperty("exception.excluded.types") != null
                ? environment.getProperty("exception.excluded.types").split("\\|")
                : new String[]{};
        /*env != null && env.equals("prod")
                &&*/
        if (
                event.getLevel().equals(Level.ERROR)
                && event.getMessage().indexOf("ErrorHandler") > -1
                &&
                (excluded.length > 0
                        ? !Arrays.stream(excluded).anyMatch(e -> event.getMessage().indexOf(e) > -1)
                        : true)) {

            String serverIp = "";
            InetAddress localInetAddress = LogUtils.getLocalInetAddress();
            if (localInetAddress != null)
                serverIp = localInetAddress.getHostAddress();

            StringBuilder message = new StringBuilder();
            message.append(String.format("【日志告警|" + appKey + "|" + enviromentType + "|" + serverIp + "】\ntraceId-" + MDC.get("traceId") + "\n" + event.getMessage() + "\n"));
            if (event.getThrowableProxy() != null && event.getThrowableProxy().getStackTraceElementProxyArray() != null) {
                Arrays.stream(event.getThrowableProxy().getStackTraceElementProxyArray())
                        .skip(0)
                        .limit(5)
                        .forEach(e -> {
                            if (e != null)
                                message.append(e.toString() + "\n");
                        });

                Arrays.stream(event.getThrowableProxy().getStackTraceElementProxyArray())
                        .skip(5)
                        .filter(e -> e != null && e.toString().indexOf("aurora") > -1)
                        //.limit(10)
                        .forEach(e -> {
                            if (e != null)
                                message.append(e.toString() + "\n");
                        });

            }
            /*LOGGER.info(message.toString());*/

            if (environment != null && environment.getProperty("exception.dingtalk.enabled") != null && Boolean.valueOf(environment.getProperty("exception.dingtalk.enabled"))
                    && environment.getProperty("exception.dingtalk.url") != null)
                DingTalkUtil.send(message.toString(), environment.getProperty("exception.dingtalk.url"));
        }

        return FilterReply.ACCEPT;
    }


}
